var express = require('express');
var router = express.Router();
let Query=require('../tools/db')
let md5=require('md5')
let uuid=require('uuid')
let {suo,api_url,getToken,verifyToken}=require('../config/config')

//注册模块
router.post('/register',async (req,res,next)=>{
    let {username='',password='',rpwd=''}=req.body
    if(username=='' || password=='' || rpwd==''){
        next('输入框不能为空')
        return
    }
    if(password != rpwd){
        next('两次输入的密码不一致')
    }
    let sql1=`SELECT * FROM e_member WHERE username='${username}'`
    let [,result1]=await Query(sql1)
    if(result1.length>0){
        next('用户名已经注册')
        return
    }else{
        let mid=uuid.v4()
        let createdate=Date.now()
        password=md5(suo+password)
        let sql2=`INSERT INTO e_member (mid,username,password,createdate) VALUES ('${mid}','${username}','${password}','${createdate}')`
        let [,result2]=await Query(sql2)
        if(result2.affectedRows>0){
            res.send({
                code:200,
                msg: "注册成功"
            })
            return
        }else{
            next('注册失败，请稍后再试')
        }
    }
})

//登录模块
router.post('/login',async (req,res,next)=>{
    let {username='',password=''}=req.body
    if(username==''  || password==''){
        next('输入框不能为空')
        return;
    }
    password=md5(suo+password)
    let sql=`SELECT * FROM e_member WHERE username='${username}' AND password='${password}'`
    let [,res1]=await Query(sql)
    if(res1.length>0){
        //生成一个token做权限验证
        let data={username,password}
        res.send({
            code:200,
            msg: "ok",
            result: getToken(data)
        })
    }else{
        next('登录失败，该用户没有注册')
    }
})


  module.exports = router;